package com.yiren.dbaa.module.practice_set.map.view.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.yiren.backstage.currency.constant.DbConstant;
import com.yiren.backstage.currency.entity.MapEntity;
import com.yiren.backstage.currency.entity.SiteEntity;
import com.yiren.backstage.currency.utils.FileUtil;
import com.yiren.backstage.currency.utils.StringUtil;
import com.yiren.backstage.db.dao.controller.TrajectDbController;
import com.yiren.backstage.db.dao.controller.UserDbController;
import com.yiren.dbaa.R;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.currency.model.ScreenModel;
import com.yiren.dbaa.module.practice_set.basestation.bean.BaseStationBean;
import com.yiren.dbaa.module.practice_set.map.view.activity.MapCollectActivity;
import com.yiren.dbaa.util.AssetCopyUtil;
import com.yiren.dbaa.util.GraphicUtil;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Describe 添加地图弹出框
 *
 * @author WRX
 * @date 2022/12/1
 */
public class AddMapDialog {

    private Activity activity;
    /*** 选择的基站索引 */
    private int baseStationIndex = 0;
    /*** 选择的考场索引 */
    private int siteIndex = 0;

    public AddMapDialog(Activity activity) {
        this.activity = activity;
    }

    /**
     * 显示地图自己采集的弹出框
     */
    public void showAddMapDialog(int userId, List<SiteEntity> siteList, List<BaseStationBean> baseStationBeans) {
        String[] baseStations = new String[baseStationBeans.size()];
        for (int i = 0; i < baseStationBeans.size(); i++) {
            baseStations[i] = baseStationBeans.get(i).getName();
        }
        AlertDialog dialog = new AlertDialog.Builder(activity).create();
        View view = LayoutInflater.from(activity).inflate(R.layout.dialog_add_map, null);
        dialog.setContentView(view);
        dialog.setView(new EditText(activity));
        dialog.show();
        // 高度占了全屏，临时给了一个高度，代码未优化
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        ScreenModel screen = GraphicUtil.getResolutionInfo(activity);
        params.width = (screen.getWidth() * 6) / 10;
//        params.height = (screen.getHeight() * 6) / 10;
        dialog.getWindow().setAttributes(params);
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_add_map);
        Spinner spBaseStation = window.findViewById(R.id.sp_base_station);
        RadioGroup rgMapType = window.findViewById(R.id.rg_map_type);
        RadioButton rbExamMap = window.findViewById(R.id.rb_exam_map);
        RadioButton rbTestMap = window.findViewById(R.id.rb_test_map);
        Spinner spMapName = window.findViewById(R.id.sp_map_name);
        EditText etMapName = window.findViewById(R.id.et_map_name);
        TextView tvCancel = window.findViewById(R.id.tv_cancel);
        TextView tvCollect = window.findViewById(R.id.tv_collect);
        ArrayAdapter<String> baseStationAdapter = new ArrayAdapter<String>(activity, R.layout.item_spinner, baseStations);
        baseStationAdapter.setDropDownViewResource(R.layout.item_spinner_dropdown);
        spBaseStation.setAdapter(baseStationAdapter);
        spBaseStation.setSelection(baseStationIndex);
        spBaseStation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                baseStationIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        //设置默认选中值
        if (null == siteList || siteList.size() == 0) {
            rbTestMap.setChecked(true);
            spMapName.setVisibility(View.GONE);
            etMapName.setVisibility(View.VISIBLE);
        } else {
            rbExamMap.setChecked(true);
            spMapName.setVisibility(View.VISIBLE);
            etMapName.setVisibility(View.GONE);
            String[] siteNames = new String[siteList.size()];
            for (int i = 0; i < siteList.size(); i++) {
                siteNames[i] = siteList.get(i).getSiteName();
            }
            ArrayAdapter<String> siteAdapter = new ArrayAdapter<String>(activity, R.layout.item_spinner, siteNames);
            baseStationAdapter.setDropDownViewResource(R.layout.item_spinner_dropdown);
            spMapName.setAdapter(siteAdapter);
            spMapName.setSelection(siteIndex);
            spMapName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    siteIndex = position;
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                }
            });
        }
        rgMapType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_exam_map:
                        spMapName.setVisibility(View.VISIBLE);
                        etMapName.setVisibility(View.GONE);
                        if (null == siteList || siteList.size() == 0) {
                            MessageBox.show(activity, "没有可选的考场");
                        }
                        break;
                    case R.id.rb_test_map:
                        spMapName.setVisibility(View.GONE);
                        etMapName.setVisibility(View.VISIBLE);
                        break;
                }
            }
        });
        tvCancel.setOnClickListener(v -> {
            dialog.dismiss();
        });
        tvCollect.setOnClickListener(v -> {
            if (rbExamMap.isChecked() && (null == siteList || siteList.size() == 0)) {
                //当前所有考场均采集了地图
                MessageBox.show(activity, "请选择训练路段或先新建考规！");
                return;
            }
            String siteCode;
            String name;
            if (rbExamMap.isChecked()) {
                //考试路段取当前选择的考场的考场码
                siteCode = siteList.get(siteIndex).getSiteCode();
                name = siteList.get(siteIndex).getSiteName();
            } else {
                //训练路段取当前时间戳为考场码
                siteCode = System.currentTimeMillis() + "";
                name = etMapName.getText().toString().trim();
                if (StringUtils.isEmpty(name)) {
                    MessageBox.show(activity, "请输入地图名称！");
                    return;
                }
            }
            //创建map文件夹，用于保存traject.db
            String mapDir = DbConstant.App_Main_Directory + userId + "/map/" + siteCode;
            File file = new File(mapDir);
            if (!file.exists()) file.mkdirs();
            DbConstant.TRAJECT_DATA_URL = mapDir + "/" + DbConstant.TRAJECT_DATA_NAME;
            //验证traject.db
            if (!FileUtil.exists(DbConstant.TRAJECT_DATA_URL)) {
                AssetCopyUtil assetCopyer = new AssetCopyUtil(activity);
                try {
                    assetCopyer.copyToPath(AddressConstant.App_Main_Directory(), userId + "/map/" + siteCode + "/" + DbConstant.TRAJECT_DATA_NAME, "data/traject/traject.db");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //这里传true，用于创建数据库
            TrajectDbController.getInstance(true);
            MapEntity map = new MapEntity(StringUtil.getUUID(), siteCode, name, userId, 0.0f, rbExamMap.isChecked() ? 1 : 2, 2, "首次发布", 2, System.currentTimeMillis(), 1, baseStationBeans.get(baseStationIndex).getId(), 0, "", baseStationBeans.get(baseStationIndex).getName());
            UserDbController.getInstance(false).insertOrReplace(map);
            activity.startActivity(new Intent(activity, MapCollectActivity.class));
            dialog.dismiss();
        });
    }

}